package com.example.edu_service.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.edu_service.entity.EduSubject;
import com.example.edu_service.entity.excel.SubjectData;
import com.example.edu_service.service.EduSubjectService;
import com.example.servicebase.exceptionhandler.ZDYException;

public class SubjectExcelListener extends AnalysisEventListener<SubjectData> {

    private EduSubjectService eduSubjectService;

    public SubjectExcelListener(EduSubjectService eduSubjectService) {
        this.eduSubjectService = eduSubjectService;
    }
    public SubjectExcelListener() {
    }


    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {

        if (subjectData==null){
            throw new ZDYException(20001,"文件为空");
        }

        EduSubject oneSubject = this.existOneSubject(eduSubjectService, subjectData.getOneSubject());

        if (oneSubject==null){

            oneSubject= new EduSubject();
            oneSubject.setParentId("0");
            oneSubject.setTitle(subjectData.getOneSubject());
            eduSubjectService.save(oneSubject);
        }
        String pid=oneSubject.getId();

        EduSubject twoSubject = this.existTwoSubject(eduSubjectService, subjectData.getTwoSubject(), pid);
        if (twoSubject==null){
            twoSubject= new EduSubject();
            twoSubject.setParentId(pid);
            twoSubject.setTitle(subjectData.getTwoSubject());
            eduSubjectService.save(twoSubject);
        }

    }

    private EduSubject existOneSubject(EduSubjectService eduSubjectService,String name){

        QueryWrapper<EduSubject> wrapper=new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id","0");
        EduSubject one = eduSubjectService.getOne(wrapper);
        return one;
    }

    private EduSubject existTwoSubject(EduSubjectService eduSubjectService,String name,
                                       String pid){

        QueryWrapper<EduSubject> wrapper=new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id",pid);
        EduSubject two = eduSubjectService.getOne(wrapper);
        return two;
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
